package com.tony.jdbc.dynamic.config;

import com.tony.jdbc.dynamic.enums.EDatasourceFrom;
import lombok.Data;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.LinkedList;
import java.util.List;

/**
 * @author tony
 * @desc 动态数据源配置
 * @date 2025/11/12 08:51
 */
@Data
@ConfigurationProperties(prefix = "spring.dynamic-datasource")
@Configuration
public class DynamicDataSourceProperties {
    /**
     * 从数据库中获取数据源列表的sql
     */
    private String datasourceSql;
    /**
     * 配置的数据源列表，可以走配置文件spring.datasources.datasourceList；也可以在getDatasourceList里自定义从主数据源查询
     */
    private EDatasourceFrom from = EDatasourceFrom.CONF;
    /**
     * 加载配置文件数据源：spring.datasources.datasourceList
     */
    private List<DataSourceProperties> datasourceList;

    /**
     * 获取所有数据源列表
     *
     * @return 数据源列表
     */
    public List<DataSourceProperties> getAllDatasourceList(JdbcTemplate jdbcTemplate) {
        List<DataSourceProperties> datasourceAllList = new LinkedList<>();
        String datasourceSql = this.getDatasourceSql();
        EDatasourceFrom from = this.getFrom();
        List<DataSourceProperties> datasourceList = this.getDatasourceList();
        if (from != null) {
            switch (from) {
                case DB:
                    datasourceAllList = jdbcTemplate.query(datasourceSql,new BeanPropertyRowMapper<>(DataSourceProperties.class));
                    break;
                case CONF:
                    if (datasourceList != null) {
                        datasourceAllList.addAll(datasourceList);
                    }
                    break;
            }
        }
        return datasourceAllList;
    }
}
